package other.xsy.pms;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.context.ScriptRuntimeContext;
import com.rkhd.platform.sdk.data.model.Opportunity;
import com.rkhd.platform.sdk.data.model.Quote;
import com.rkhd.platform.sdk.exception.ApiEntityServiceException;
import com.rkhd.platform.sdk.exception.ScriptBusinessException;
import com.rkhd.platform.sdk.exception.XsyHttpException;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.model.XObject;
import com.rkhd.platform.sdk.trigger.DataResult;
import com.rkhd.platform.sdk.trigger.Trigger;
import com.rkhd.platform.sdk.trigger.TriggerRequest;
import com.rkhd.platform.sdk.trigger.TriggerResponse;
import org.apache.commons.lang.StringUtils;
import other.xsy.pms.utils.ComUtils;
import other.xsy.pms.utils.HCXObjectService;
import other.xsy.pms.utils.PromotionApiUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @Description 创建报价单判断机会点是否已经在PMS设置概算
 * @Author 黎炎松
 * 2024-06-04 10:05
 */
public class QuoteAddBeforeTrigger implements Trigger {

    private static HCXObjectService hcxObjectService = new HCXObjectService();
    private static final Logger logger = LoggerFactory.getLogger();
    private static String LOGGER_MSG = "创建报价单设置机会PMS概算信息 ==> ";

    @Override
    public TriggerResponse execute(TriggerRequest request) throws ScriptBusinessException {
        logger.debug(LOGGER_MSG + " 触发开始 ");
        List<XObject> dataList = request.getDataList();
        List<DataResult> dataResultList = new ArrayList<>();
        List<Quote> quoteList = new ArrayList<>();
        for (XObject xObject : dataList) {
            Quote quote = (Quote) xObject;
            quoteList.add(quote);
            dataResultList.add(new DataResult(true, "", xObject));
        }
        dataResultList.set(0, setQuoteEstimate(quoteList.get(0)));
        return new TriggerResponse(true, "处理完成", dataResultList);
    }

    public static void main(String[] args) throws ApiEntityServiceException {
        Quote quote = new Quote();
        quote.setId(3474017510152846L);
        quote = hcxObjectService.get(quote);
        //quote.setEntityType(3203859641306480L);
        //quote.setQuotationEntityRelOpportunity(3281374671051400L);


        QuoteAddBeforeTrigger quoteAddTrigger = new QuoteAddBeforeTrigger();
        quoteAddTrigger.setQuoteEstimate(quote);
    }


    /**
     * 设置报价单机会概算信息
     * @param quote
     */
    public DataResult setQuoteEstimate(Quote quote){
        try {
            logger.debug(LOGGER_MSG + " 处理开始:" + quote);
            // 获取报价单机会点
            Long opportunityId = quote.getQuotationEntityRelOpportunity();
            Long entityType = quote.getEntityType();

            // 白名单用户不校验
            if (Objects.equals(isWhiteListUser(), "1")) {
                return new DataResult(true,"校验完成" , quote);
            }

            // 判断类型只拦截 项目类型
            if (entityType != 3203859641306480L) {
                logger.debug(LOGGER_MSG + "不是项目类型，无需拦截");
                return new DataResult(true,"校验完成" , quote);
            }

            // 获取业务机会的 sf_id
            String opportunityIds = opportunityId.toString();
            String sql = "select id,SF_ID__c from opportunity where id = " + opportunityId;
            Opportunity opportunity = hcxObjectService.queryOne(sql);
            if (opportunity != null && opportunity.getSF_ID__c() != null) {
                opportunityIds += "," + opportunity.getSF_ID__c();
            }

            // 查询PMS概算信息
            JSONObject response = PromotionApiUtil.getEstimateData(opportunityIds);
            if (!Objects.equals(response.getInteger("code"),0)) {
                logger.debug(LOGGER_MSG + "查询机会PMS概算信息异常");
                return new DataResult(false, "查询机会PMS概算信息异常", quote);
            }

            // 判断值是否正常 preNo 为null 则代表当前机会点没有在 PMS 进行概算设置
            JSONObject reqData = response.getJSONObject("data");
            String preNo = reqData.getString("preNo");
            logger.debug(LOGGER_MSG + "preNo: " + preNo);
            if (StringUtils.isBlank(preNo)) {
                logger.debug(LOGGER_MSG + "当前机会在PMS没有提交或审批通过的概算,需要先在PMS系统内完成操作");
                return new DataResult(false, "报价需有审批中或审批通过的概算，请先完成PMS系统内操作，谢谢！", quote);
            }

            // 获取分类为 总计 的数据，设置字段信息
            JSONArray profitMeasurementList = reqData.getJSONArray("profitMeasurementList");
            if (profitMeasurementList == null) {
                logger.info(LOGGER_MSG + "当前机会在PMS没有提交或审批通过的概算,需要先在PMS系统内完成操作");
                return new DataResult(false, "报价需有审批中或审批通过的概算，请先完成PMS系统内操作，谢谢！", quote);
            }

            logger.debug(LOGGER_MSG + "profitMeasurementList: " + profitMeasurementList);
            Object profitObj = profitMeasurementList.stream().filter(v -> {
                JSONObject object = (JSONObject) v;
                return object.getInteger("totalType") == 2;
            }).findFirst().orElse(null);
            if (profitObj != null) {
                JSONObject profitData = (JSONObject) profitObj;
                quote.setTotalType__c(2); // 分类统计类型 1-分类汇总，2-总计
                quote.setPmsProjectNo__c(preNo); // 项目编号
                quote.setIsCoreProducts__c(profitData.getBoolean("isCoreProducts") == true ? 1 : 2); // 是否核心产品 1: 是  2: 否
                quote.setGrossProfitCount__c(profitData.getDouble("grossProfitCount")); // 项目毛利 grossProfitCount__c
                quote.setGrossProfitMarginCount__c(profitData.getDouble("grossProfitMarginCount")); // 项目毛利率 grossProfitMarginCount__c
                quote.setNetProfitContributedByTheProject__c(profitData.getDouble("netProfitContributedByTheProject")); // 项目贡献利润率 netProfitContributedByTheProject__c
                quote.setProjectContributionRate__c(profitData.getDouble("projectContributionRate")); // 项目贡献利润 projectContributionRate__c
            }

            logger.info(LOGGER_MSG + "quote: " + quote);
            logger.info(LOGGER_MSG + "处理成功");
            return new DataResult(true,"校验完成" , quote);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(LOGGER_MSG + "处理异常");
            return new DataResult(false, "处理异常", quote);
        }
    }

    /**
     * 是否是白名单用户
     * @return
     * @throws ApiEntityServiceException
     */
    public String isWhiteListUser() throws IOException, XsyHttpException {
        String isWhiteUser = "0";
        ScriptRuntimeContext src = ScriptRuntimeContext.instance();
        long userId = src.getUserId();
        logger.debug("userId: " + userId);
        if (userId != -1) {
            JSONObject responseData = ComUtils.queryUserRole(userId);
            List<JSONObject> userRoleLists = JSONArray.parseArray(responseData.getString("records"), JSONObject.class);
            logger.debug("userRoleLists: " + userRoleLists);

            // 判断是否是这两个角色的用户 管理员: 160401000 商务: 3214956314643734 报价单测试:3440442528242323
            List<Long> roleList = Arrays.asList(160401000L, 3214956314643734L, 3440442528242323L);
            for (JSONObject userRoleList : userRoleLists) {
                if (roleList.contains(userRoleList.getLong("id"))) {
                    isWhiteUser = "1";
                    return isWhiteUser;
                }
            }
        }
        return isWhiteUser;
    }

}
